package top.bug.blog.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.bug.blog.common.UserContext;

import java.time.LocalDateTime;

/**
 * @author <a href="https://github.com/jiusi66">九思.</a>
 * @email 10837907@qq.com
 * @from <a href="https://www.52bug.top">递归茶馆-www.52bug.top</a>
 * @description MyBatisPlus 配置类
 */
@Configuration
public class MyBatisPlusConfig implements MetaObjectHandler {
    /**
     * 插入时字段填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        metaObject.setValue("createOn", LocalDateTime.now());
        metaObject.setValue("updateOn", LocalDateTime.now());
        metaObject.setValue("createBy", UserContext.getUserId());
        metaObject.setValue("updateBy", UserContext.getUserId());
    }

    /**
     * 更新时字段填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        metaObject.setValue("updateOn", LocalDateTime.now());
        metaObject.setValue("updateBy", UserContext.getUserId());
    }

    /**
     * 配置分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 向MybatisPlus拦截器链中添加分页拦截器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}